package main

import (
	"bufio"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"net/http"
	"os"
	"strings"
)

const (
	DSN = "root:Huixj2023!@#@(101.37.32.199:184)/medicine_handle?charset=utf8mb4&parseTime=True&loc=Local"
)

func main() {
	db, err := gorm.Open(mysql.Open(DSN), &gorm.Config{})
	if err != nil {
		fmt.Printf("db connect error: %s\n", err.Error())
		return
	}
	var result []string
	var content strings.Builder
	db.Raw("select product_img from t_sys_base_product where product_img is not null").Scan(&result)
	for _, str := range result {
		splitImg := strings.Split(str, ",")
		for _, img := range splitImg {
			code := download(img)
			if code < 200 || code > 399 {
				content.WriteString(img + "\n")
			}
		}
	}
	write(content.String())
}

func write(errResult string) {
	file, err := os.OpenFile("output.txt", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
		fmt.Printf("Error opening file:%s\n", err.Error())
		return
	}
	defer file.Close()
	writer := bufio.NewWriter(file)
	writer.WriteString(errResult)
	writer.Flush()
	fmt.Println("Successfully wrote strings to file.")
}

func download(str string) int {
	resp, err := http.Head(str)
	if err != nil {
		return http.StatusNotFound
	}
	return resp.StatusCode
}
